<template>
  <div>
    <div class="mt-3 d-flex justify-content-end">
      <el-button class="my-1" icon="el-icon-refresh" @click="getData()">刷新</el-button>
      <el-button @click="editRepay" class="my-1" icon="fa fa-edit">编辑</el-button>
    </div>
    <el-table
      :data="datumRepayList"
      :loading="loading"
      :height="dialogMaxheight"
      border
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column label="还款时间" prop="payTime" align="center"></el-table-column>
      <el-table-column label="应还本金（元）" prop="capital" align="center"></el-table-column>
      <el-table-column
        label="已还金额（元）"
        prop="repay_funds_total"
        align="center"
      ></el-table-column>
      <el-table-column label="剩余应还（元）" align="center">
        <template v-slot="scope">
          {{ sub(scope.row.capital, scope.row.repay_funds_total) }}
        </template>
      </el-table-column>
    </el-table>

    <repay-plan-dialog
      ref="repay"
      :visible.sync="repayVisible"
      :repay-funds="related.reply_funds"
      :query-id="queryId"
      :view-mode="false"
      @success="handlerSuccess()"
    ></repay-plan-dialog>
  </div>
</template>

<script>
import { enumRepayType } from '@/credit/plugins/enum'
import RepayPlanDialog from '@/credit/components/repay/RepayPlanDialog'
import { mul, sub } from '@vimi/utils-tool'
export default {
  components: { RepayPlanDialog },
  props: {
    queryId: String,
  },
  data() {
    return {
      sub,
      enumRepayType,
      dialogMaxheight: 600,
      datumRepayList: [],
      tableName: 'datum_repay_list_view_new',
      loading: false,
      repayVisible: false,
      repayType: '',
      repayList: [],
      related: {},

      editVisible: false,
      repayYear: 0,

      saveLoading: false,
    }
  },
  computed: {
    repayFunds() {
      return mul(this.related.reply_funds, 1e4)
    },
  },
  watch: {
    queryId: {
      handler: function (val) {
        if (val) {
          this.getData()
        }
      },
      immediate: true,
    },
  },
  created() {
    this.initDialogMaxHeight()
  },
  mounted() {},
  methods: {
    handlerSuccess() {
      this.getData()
      this.$emit('success', true)
    },
    // async handlePass() {
    //   const [captialSum] = this.getSums(this.repayList)
    //   if (captialSum !== this.repayFunds) {
    //     return this.$message.error(
    //       `还款计划本金合计金额（${captialSum}元）与放款金额（${this.repayFunds}元）不相等，请先调整还款计划！`
    //     )
    //   }
    //   this.saveLoading = true
    //   await this.$api.updateData(this.$serviceName, 'customer_related', this.queryId, {
    //     repay_method: this.repayType,
    //   })
    //   await this.$refs.repay.addRepayList()
    //   this.saveLoading = false
    //   this.$message.success('保存成功')
    //   this.beforeClose()
    //   this.getData()
    // },

    editRepay() {
      this.repayVisible = true
    },
    async getData() {
      this.related = {}
      this.loading = true
      await this.$api
        .getDataFromId(this.$serviceName, 'customer_related', this.queryId)
        .then(res => {
          const data = res?.data ?? {}
          this.related = data
          this.repayType = data.repay_method
          this.repayYear = Math.ceil(+data.months / 12)
        })
      this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          {
            'customer_related_id.eq': this.queryId,
          },
          { pay_time: 'asc' }
        )
        .then(res => {
          this.datumRepayList = (res?.data ?? []).map(item => {
            item.payTime = this.$utils.dateFormat(item.pay_time, 'yyyy-MM-dd')
            return item
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    initDialogMaxHeight() {
      const clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight
      this.dialogMaxheight = clientHeight - 400
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if ([1, 2].includes(index)) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          } else {
            sums[index] = '-'
          }
        } else if (index === 3) {
          sums[index] = sub(sums[1], sums[2])
        } else {
          sums[index] = '-'
        }
      })
      return sums
    },
  },
}
</script>

<style lang="scss" scoped>
.text-center /deep/ .el-input__inner {
  text-align: center;
}
.row-sum {
  background-color: $gray-100;
  padding-right: 20px;
  display: flex;
  flex-wrap: nowrap;
  .row-sum-td {
    flex: 1;
    padding: 0.5rem 0.25rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
  }
}
</style>
